<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <title>职员管理</title>
    <link rel="stylesheet" href="./css/bootstrap.css">
    <script src="./js/jQuery-3.7.1.min.js"></script>
    <script src="./js/bootstrap.min.js"></script>
    <script src="./js/layer/layer.js"></script>
</head>
<body>
<div class="container">
    <h3>职员列表</h3>
    <hr>
    <!-- 搜索区域 -->
    <div class="row mb-3">
        <div class="col-12">
            <form class="form-inline" id="searchForm">
                <div class="form-group mr-3">
                    <input type="text" class="form-control" id="searchEname" placeholder="职员姓名">
                </div>
                <div class="form-group mr-3">
                    <input type="text" class="form-control" id="searchJob" placeholder="职位">
                </div>
                <div class="form-group mr-3">
                    <select class="form-control" id="searchDeptno">
                        <option value="">选择部门</option>
                    </select>
                </div>
                <button type="button" class="btn btn-primary mr-2" id="btnSearch">搜索</button>
                <button type="button" class="btn btn-secondary mr-2" id="btnReset">重置</button>
                <button type="button" class="btn btn-primary" id="btnAddDialog">添加职员</button>
            </form>
        </div>
    </div>

    <!-- 数据表格 -->
    <table>
        <colgroup>
            <col width="150">
            <col width="200">
            <col>
        </colgroup>
        <thead>
        <th>职员编号</th>
        <th>职员姓名</th>
        <th>职位</th>
        <th>入职日期</th>
        <th>薪资</th>
        <th>奖金</th>
        <th>所属部门</th>
        <th width="180">操作</th>
        </thead>
        <tbody id="tbody">

        </tbody>
    </table>
</div>


<!-- 添加职员对话框 -->
<div class="modal fade" id="addEmpDialog" tabindex="-1" aria-hidden="true">
    <div class="modal-dialog modal-dialog-centered">
        <div class="modal-content">
            <div class="modal-header">
                <h5 class="modal-title">添加职员</h5>
                <button type="button" class="close" data-dismiss="modal" aria-label="Close">
                    <span aria-hidden="true">×</span>
                </button>
            </div>
            <div class="modal-body">
                <form>
                    <div class="form-group row">
                        <label class="col-sm-3 col-form-label text-md-right">职员姓名</label>
                        <div class="col-sm-8">
                            <input type="text" placeholder="请输入职员姓名" class="form-control" id="ename">
                        </div>
                    </div>
                    <div class="form-group row">
                        <label class="col-sm-3 col-form-label text-md-right">职位</label>
                        <div class="col-sm-8">
                            <input type="text" placeholder="请输入职位" class="form-control" id="job">
                        </div>
                    </div>
                    <div class="form-group row">
                        <label class="col-sm-3 col-form-label text-md-right">入职日期</label>
                        <div class="col-sm-8">
                            <input type="date" class="form-control" id="hiredate">
                        </div>
                    </div>
                    <div class="form-group row">
                        <label class="col-sm-3 col-form-label text-md-right">薪资</label>
                        <div class="col-sm-8">
                            <input type="number" placeholder="请输入薪资" class="form-control" id="sal">
                        </div>
                    </div>
                    <div class="form-group row">
                        <label class="col-sm-3 col-form-label text-md-right">奖金</label>
                        <div class="col-sm-8">
                            <input type="number" placeholder="请输入奖金" class="form-control" id="comm">
                        </div>
                    </div>
                    <div class="form-group row">
                        <label class="col-sm-3 col-form-label text-md-right">所属部门</label>
                        <div class="col-sm-8">
                            <select class="form-control" id="deptno"></select>
                        </div>
                    </div>
                </form>
            </div>
            <div class="modal-footer">
                <button type="button" class="btn btn-secondary" data-dismiss="modal">取消</button>
                <button type="button" id="btnConfirm" class="btn btn-primary">确定</button>
            </div>
        </div>
    </div>
</div>

<!-- 编辑职员对话框 -->
<div class="modal fade" id="updateEmpDialog" tabindex="-1" aria-hidden="true">
    <div class="modal-dialog modal-dialog-centered">
        <div class="modal-content">
            <div class="modal-header">
                <h5 class="modal-title">编辑职员</h5>
                <button type="button" class="close" data-dismiss="modal" aria-label="Close">
                    <span aria-hidden="true">×</span>
                </button>
            </div>
            <div class="modal-body">
                <form>
                    <div class="form-group row">
                        <label class="col-sm-3 col-form-label text-md-right">职员编号</label>
                        <div class="col-sm-8">
                            <input type="text" readonly class="form-control-plaintext" id="txtEmpno">
                        </div>
                    </div>
                    <div class="form-group row">
                        <label class="col-sm-3 col-form-label text-md-right">职员姓名</label>
                        <div class="col-sm-8">
                            <input type="text" placeholder="请输入职员姓名" class="form-control" id="txtEname">
                        </div>
                    </div>
                    <div class="form-group row">
                        <label class="col-sm-3 col-form-label text-md-right">职位</label>
                        <div class="col-sm-8">
                            <input type="text" placeholder="请输入职位" class="form-control" id="txtJob">
                        </div>
                    </div>
                    <div class="form-group row">
                        <label class="col-sm-3 col-form-label text-md-right">入职日期</label>
                        <div class="col-sm-8">
                            <input type="date" class="form-control" id="txtHiredate">
                        </div>
                    </div>
                    <div class="form-group row">
                        <label class="col-sm-3 col-form-label text-md-right">薪资</label>
                        <div class="col-sm-8">
                            <input type="number" placeholder="请输入薪资" class="form-control" id="txtSal">
                        </div>
                    </div>
                    <div class="form-group row">
                        <label class="col-sm-3 col-form-label text-md-right">奖金</label>
                        <div class="col-sm-8">
                            <input type="number" placeholder="请输入奖金" class="form-control" id="txtComm">
                        </div>
                    </div>
                    <div class="form-group row">
                        <label class="col-sm-3 col-form-label text-md-right">所属部门</label>
                        <div class="col-sm-8">
                            <select class="form-control" id="txtDeptno"></select>
                        </div>
                    </div>
                </form>
            </div>
            <div class="modal-footer">
                <button type="button" class="btn btn-secondary" data-dismiss="modal">取消</button>
                <button type="button" id="btnUpdate" class="btn btn-primary">确定</button>
            </div>
        </div>
    </div>
</div>
</body>
<script>
    // 页面初始化
    $(function() {
        // 初始化加载
        loadDeptOptions();
        emp_list();

        // 搜索按钮点击事件
        $('#btnSearch').click(function() {
            doSearch();
        });

        // 回车键触发搜索
        $('#searchForm input').keypress(function(e) {
            if(e.which == 13) {
                e.preventDefault(); // 阻止表单提交
                doSearch();
            }
        });

        // 重置按钮点击事件
        $('#btnReset').click(function() {
            $('#searchForm')[0].reset();
            emp_list();
        });

        // 添加职员按钮点击事件
        $('#btnAddDialog').click(function () {
            clearAddForm();
            $('#addEmpDialog').modal('show');
        });
    });

    // 执行搜索
    function doSearch() {
        let params = {};
        let ename = $('#searchEname').val().trim();
        let job = $('#searchJob').val().trim();
        let deptno = $('#searchDeptno').val();

        // 添加日志，查看搜索参数
        console.log('搜索条件:', {ename, job, deptno});

        if(ename) params.ename = ename;
        if(job) params.job = job;
        if(deptno) params.deptno = deptno;

        let loadIndex = layer.load(1, {
            shade: [0.3, '#fff']
        });

        $.ajax({
            url: 'emp/searchEmp',
            type: 'POST',
            contentType: 'application/json',
            data: JSON.stringify(params),
            success: function(res) {
                layer.close(loadIndex);
                console.log('搜索结果:', res); // 添加日志

                if(res.code == '200') {
                    // 确保搜索结果只显示符合条件的数据
                    let filteredData = res.data;

                    // 根据部门编号筛选
                    if(deptno) {
                        filteredData = res.data.filter(item => item.deptno == deptno);
                    }

                    // 根据姓名筛选
                    if(ename) {
                        filteredData = filteredData.filter(item =>
                            item.ename.toLowerCase().includes(ename.toLowerCase())
                        );
                    }

                    // 根据职位筛选
                    if(job) {
                        filteredData = filteredData.filter(item =>
                            item.job.toLowerCase().includes(job.toLowerCase())
                        );
                    }

                    if(filteredData && filteredData.length > 0) {
                        updateTableData(filteredData);
                        layer.msg('搜索成功', {icon: 1});
                    } else {
                        $('#tbody').html('<tr><td colspan="8" class="text-center">暂无匹配数据</td></tr>');
                        layer.msg('未找到匹配的数据', {icon: 0});
                    }
                } else {
                    layer.msg(res.msg || '搜索失败', {icon: 2});
                }
            },
            error: function(xhr, status, error) {
                layer.close(loadIndex);
                console.error('搜索错误:', error);
                layer.msg('系统错误，请稍后重试', {icon: 2});
            }
        });
    }

    // 更新表格数据
    function updateTableData(data) {
        let html = '';
        if(data && data.length > 0) {
            data.forEach(item => {
                html += `<tr>
                <td>${item.empno || ''}</td>
                <td>${item.ename || ''}</td>
                <td>${item.job || ''}</td>
                <td>${formatDate(item.hiredate) || ''}</td>
                <td>${item.sal || '0'}</td>
                <td>${item.comm || '0'}</td>
                <td>${item.dname || '未分配'}</td>
                <td>
                    <button type="button" onclick="emp_update(${item.empno})" class="btn btn-info btn-sm">编辑</button>
                    <button type="button" onclick="emp_del('${item.ename}',${item.empno})" class="btn btn-danger btn-sm">删除</button>
                </td>
            </tr>`;
            });
        } else {
            html = '<tr><td colspan="8" class="text-center">暂无匹配数据</td></tr>';
        }
        $('#tbody').html(html);
    }

    // 加载部门下拉列表
    function loadDeptOptions() {
        $.getJSON('dept/listEmp', function(res) {
            if(res.code === '200') {
                let html = '<option value="">请选择部门</option>';
                res.data.forEach(dept => {
                    html += `<option value="${dept.deptno}">${dept.dname}</option>`;
                });
                $('#searchDeptno, #deptno, #txtDeptno').html(html);
            }
        });
    }

    // 添加职员
    $('#btnConfirm').click(function() {
        if(!validateForm('#ename', '#job', '#hiredate', '#sal', '#deptno')) {
            return;
        }

        let formData = {
            ename: $('#ename').val().trim(),
            job: $('#job').val().trim(),
            hiredate: $('#hiredate').val(),
            sal: $('#sal').val(),
            deptno: $('#deptno').val()
        };

        if($('#comm').val()) {
            formData.comm = $('#comm').val();
        }

        $.ajax({
            url: 'emp/addEmp',
            type: 'POST',
            contentType: 'application/json',
            data: JSON.stringify(formData),
            success: function(res) {
                if(res.code === '200') {
                    layer.msg('添加成功', {icon: 1, time: 500}, function() {
                        $('#addEmpDialog').modal('hide');
                        clearAddForm();
                        emp_list();
                    });
                } else {
                    layer.msg(res.msg || '添加失败', {icon: 2});
                }
            },        error: function() {
                layer.msg('系统错误，请稍后重试', {icon: 2});
            }
        });
    });

    // 更新职员
    $('#btnUpdate').click(function() {
        if(!validateForm('#txtEname', '#txtJob', '#txtHiredate', '#txtSal', '#txtDeptno')) {
            return;
        }

        let formData = {
            empno: $('#txtEmpno').val(),
            ename: $('#txtEname').val().trim(),
            job: $('#txtJob').val().trim(),
            hiredate: $('#txtHiredate').val(),
            sal: $('#txtSal').val(),
            deptno: $('#txtDeptno').val()
        };

        if($('#txtComm').val()) {
            formData.comm = $('#txtComm').val();
        }

        $.ajax({
            url: 'emp/updateEmp',
            type: 'POST',
            contentType: 'application/json',
            data: JSON.stringify(formData),
            success: function(res) {
                if(res.code === '200') {
                    layer.msg('更新成功', {icon: 1, time: 500}, function() {
                        $('#updateEmpDialog').modal('hide');
                        clearEditForm();
                        emp_list();
                    });
                } else {
                    layer.msg(res.msg || '更新失败', {icon: 2});
                }
            },
            error: function() {
                layer.msg('系统错误，请稍后重试', {icon: 2});
            }
        });
    });

    // 表单验证
    function validateForm(...fields) {
        for(let field of fields) {
            if(!$(field).val()) {
                layer.msg('请填写必填信息', {icon: 2});
                return false;
            }
        }
        return true;
    }

    // 清空添加表单
    function clearAddForm() {
        $('#ename').val('');
        $('#job').val('');
        $('#hiredate').val('');
        $('#sal').val('');
        $('#comm').val('');
        $('#deptno').val('');
    }

    // 清空编辑表单
    function clearEditForm() {
        $('#txtEmpno').val('');
        $('#txtEname').val('');
        $('#txtJob').val('');
        $('#txtHiredate').val('');
        $('#txtSal').val('');
        $('#txtComm').val('');
        $('#txtDeptno').val('');
    }

    // 加载职员列表
    function emp_list() {
        $.getJSON('emp/listEmp', function(res) {
            updateTableData(res.data);
        }).fail(function(jqXHR, textStatus, errorThrown) {
            console.error('获取职员列表失败:', textStatus, errorThrown);
            $('#tbody').html('<tr><td colspan="8" class="text-center">获取数据失败</td></tr>');
        });
    }

    // 删除职员
    function emp_del(ename, empno) {
        layer.confirm(`确定删除职员"${ename}"的信息吗？`, {icon: 3, title: '删除提示'}, function(index) {
            $.getJSON('emp/delEmp/' + empno, function(res) {
                if(res.code === '200') {
                    layer.msg('删除成功', {icon: 1, time: 500}, function() {
                        layer.close(index);
                        emp_list();
                    });
                } else {
                    layer.msg(res.msg || '删除失败', {icon: 2});
                }
            });
        });
    }

    // 编辑职员
    function emp_update(empno) {
        $.getJSON(`emp/getEmp/${empno}`, function(res) {
            if(res.code === '200') {
                let emp = res.data;
                $('#txtEmpno').val(emp.empno);
                $('#txtEname').val(emp.ename);
                $('#txtJob').val(emp.job);
                $('#txtHiredate').val(formatDate(emp.hiredate));
                $('#txtSal').val(emp.sal);
                $('#txtComm').val(emp.comm);
                $('#txtDeptno').val(emp.deptno);
                $('#updateEmpDialog').modal('show');
            }
        });
    }

    // 日期格式化
    function formatDate(date) {
        if(!date) return '';
        try {
            const d = new Date(date);
            if(isNaN(d.getTime())) return '';
            return d.getFullYear() + '-'
                + String(d.getMonth() + 1).padStart(2, '0') + '-'
                + String(d.getDate()).padStart(2, '0');
        } catch(e) {
            console.error('日期格式化错误:', e);
            return '';
        }
    }
</script>
</html>